package com.huitone.smspfm.context.utils;



import com.bin.common.utils.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.io.File;

public class ContextUtils {

	private static final Logger logger = LogManager.getLogger(ContextUtils.class);

	private ApplicationContext context = null;
	
	private static ContextUtils contextUtils = new ContextUtils();
	
	public static ContextUtils getInstance() {
		return contextUtils;
	}

	private ContextUtils() {
		init();
	}
	
	public void reload() {
		context = null;
		init();
	}
	
	public void init() {
		if (context == null) {

			String contextFilePath = System.getProperty("application.context.file.path");
			if (!StringUtils.isEmpty(contextFilePath)) {
				logger.info("application.context.file.path:" + contextFilePath);
				context = new FileSystemXmlApplicationContext(new File(contextFilePath).toURI().toString());
			} else {
				context = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
			}
		}
	}
	
	public Object getBean(String name) {
		
		Object bean = null;
		
		if (context.containsBean(name)) {
			bean = context.getBean(name);
		}
		
		return bean;
	}
	
	public static Object getBean2(String name) {
		return ContextUtils.getInstance().getBean(name);
	}
	
	public static <T> T getBean2(Class<T> requiredType) {
		return ContextUtils.getInstance().getBean(requiredType);
	}
	
	public <T> T getBean(Class<T> requiredType) {
		
		return context.getBean(requiredType);
	}
	
}
